﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using AvaAI批量点评系统.Services;
using Avalonia.Platform.Storage;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using Avalonia.Media.Imaging;

namespace AvaAI批量点评系统.ViewModels;

public partial class MainViewModel : ViewModelBase
{
    private readonly AliCloudAIService _aiService;
    private readonly QwenVLService _qwenVLService;
    private readonly ExcelService _excelService;
    private readonly ImageService _imageService;
    private readonly TemplateService _templateService;
    private readonly CourseIntroductionService _courseIntroductionService;

    [ObservableProperty]
    private string _greeting = "AI点评Excel表系统";

    // 批量点评生成相关属性
    [ObservableProperty]
    private string _selectedSubject = "乐高机器人搭建";

    [ObservableProperty]
    private string _startGrade = "三年级";

    [ObservableProperty]
    private string _endGrade = "三年级";

    [ObservableProperty]
    private string _difficulty = "入门";

    [ObservableProperty]
    private int _generateCount = 10;

    [ObservableProperty]
    private string _courseInfo = "课程: 乐高机器人搭建 | 学生: 10人";

    // AI评语扩写相关属性
    [ObservableProperty]
    private string? _selectedExcelPath;

    [ObservableProperty]
    private bool _hasSelectedExcel = false;

    [ObservableProperty]
    private string _excelUploadStatus = "未选择Excel文件";

    [ObservableProperty]
    private string _selectedExcelFileName = string.Empty;

    [ObservableProperty]
    private string? _selectedTemplatePath;

    // 单张图片识别相关属性
    [ObservableProperty]
    private string? _selectedImagePath;

    [ObservableProperty]
    private bool _hasSelectedImage = false;

    [ObservableProperty]
    private string _imageUploadStatus = "未选择图片";

    [ObservableProperty]
    private string _selectedImageFileName = string.Empty;

    [ObservableProperty]
    private bool _showImagePreview = false;

    [ObservableProperty]
    private Bitmap? _imagePreviewBitmap;

    [ObservableProperty]
    private bool _imagePreviewLoading = false;

    [ObservableProperty]
    private string _recognizedStudents = "识别到 10名学生";

    // 输出结果
    [ObservableProperty]
    private string _outputResult = string.Empty;

    [ObservableProperty]
    private bool _isProcessing = false;

    // 新增：数据预览相关属性
    [ObservableProperty]
    private bool _hasPreviewData = false;

    [ObservableProperty]
    private string _previewCourseName = string.Empty;

    [ObservableProperty]
    private string _previewGrade = string.Empty;

    [ObservableProperty]
    private string _previewDifficulty = string.Empty;

    [ObservableProperty]
    private List<string> _previewStudentNames = new();

    [ObservableProperty]
    private string _previewSummary = string.Empty;

    // 新增：格式化的学生名单显示字符串
    [ObservableProperty]
    private string _previewStudentNamesDisplay = string.Empty;

    // 新增：可编辑的学生名单字符串
    [ObservableProperty]
    private string _editableStudentNames = string.Empty;

    // 新增：AI模型选择
    [ObservableProperty]
    private string _selectedAIModel = "Qwen-VL-Max (推荐)";

    // 新增：AI评语扩写相关属性
    [ObservableProperty]
    private string _studentNameForComment = string.Empty;



    // 新增：生成的评语相关属性
    [ObservableProperty]
    private string _generatedComment = string.Empty;

    [ObservableProperty]
    private bool _hasGeneratedComment = false;

    // 新增：进度显示相关属性
    [ObservableProperty]
    private int _totalProgress = 0;

    [ObservableProperty]
    private int _currentProgress = 0;

    [ObservableProperty]
    private string _currentTaskDescription = string.Empty;

    [ObservableProperty]
    private bool _showProgress = false;

    [ObservableProperty]
    private double _progressPercentage = 0.0;

    // 新增：课程介绍相关属性
    [ObservableProperty]
    private string _courseIntroduction = string.Empty;

    [ObservableProperty]
    private bool _hasCourseIntroduction = false;

    [ObservableProperty]
    private bool _showCourseIntroduction = false;

    // 新增：预览界面相关属性
    [ObservableProperty]
    private bool _showPreviewView = false;

    [ObservableProperty]
    private List<StudentComment> _lastGeneratedComments = new();

    // 计算属性：是否有生成的评语
    public bool HasGeneratedComments => LastGeneratedComments?.Count > 0;



    // 新增：当前学生数量（实时计算）
    public int CurrentStudentCount
    {
        get
        {
            var currentNames = GetCurrentStudentNames();
            return currentNames.Count;
        }
    }

    public ObservableCollection<string> Subjects { get; } = new()
    {
        "未识别",
        "乐高机器人搭建",
        "科学实验", 
        "GESP图形化编程（一）级",
        "GESP图形化编程（二）级",
        "GESP图形化编程（三）级",
        "GESP-Python（一）级",
        "GESP-Python（二）级", 
        "GESP-Python（三）级",
        "GESP-C++（一）级",
        "GESP-C++（二）级",
        "GESP-C++（三）级",
        "传感器搭建",
        "3D打印笔模型设计",
        "智能穿越机器人",
        "趣味思维",
        "创意创客电路",
        "车航模"
    };

    public ObservableCollection<string> Grades { get; } = new()
    {
        "未识别", "一年级", "二年级", "三年级", "四年级", "五年级", "六年级"
    };

    public ObservableCollection<string> Difficulties { get; } = new()
    {
        "未识别", "入门", "基础", "提高", "竞赛"
    };

    public ObservableCollection<string> AIModels { get; } = new()
    {
        "Qwen-VL-Max (推荐)",
        "Qwen-Omni-Turbo (原版)"
    };

    public MainViewModel()
    {
        _aiService = new AliCloudAIService();
        _qwenVLService = new QwenVLService();
        _excelService = new ExcelService();
        _imageService = new ImageService();
        _templateService = new TemplateService();
        _courseIntroductionService = new CourseIntroductionService();
    }

    // 当EditableStudentNames改变时，通知CurrentStudentCount也需要更新
    partial void OnEditableStudentNamesChanged(string value)
    {
        OnPropertyChanged(nameof(CurrentStudentCount));
    }

    // 当SelectedImagePath改变时，更新图片状态
    partial void OnSelectedImagePathChanged(string? value)
    {
        if (!string.IsNullOrEmpty(value) && File.Exists(value))
        {
            HasSelectedImage = true;
            SelectedImageFileName = Path.GetFileName(value);
            ImageUploadStatus = "✅ 图片已加载";
            
            // 异步加载图片预览
            _ = LoadImagePreviewAsync(value);
        }
        else
        {
            HasSelectedImage = false;
            SelectedImageFileName = string.Empty;
            ImageUploadStatus = "未选择图片";
            ShowImagePreview = false;
            ImagePreviewLoading = false;
            ImagePreviewBitmap?.Dispose();
            ImagePreviewBitmap = null;
        }
    }

    private async Task LoadImagePreviewAsync(string imagePath)
    {
        try
        {
            ImagePreviewLoading = true;
            ShowImagePreview = false;
            
            // 在后台线程加载图片
            await Task.Run(() =>
            {
                try
                {
                    var bitmap = new Bitmap(imagePath);
                    
                    // 切换回UI线程更新界面
                    Avalonia.Threading.Dispatcher.UIThread.Post(() =>
                    {
                        ImagePreviewBitmap?.Dispose();
                        ImagePreviewBitmap = bitmap;
                        ShowImagePreview = true;
                        ImagePreviewLoading = false;
                    });
                }
                catch (Exception ex)
                {
                    // 图片加载失败
                    Avalonia.Threading.Dispatcher.UIThread.Post(() =>
                    {
                        ImagePreviewBitmap = null;
                        ShowImagePreview = false;
                        ImagePreviewLoading = false;
                        ImageUploadStatus = "⚠️ 图片加载失败";
                    });
                }
            });
        }
        catch (Exception ex)
        {
            ImagePreviewLoading = false;
            ShowImagePreview = false;
            ImageUploadStatus = "⚠️ 图片加载失败";
        }
    }

    // 当SelectedExcelPath改变时，更新Excel状态
    partial void OnSelectedExcelPathChanged(string? value)
    {
        if (!string.IsNullOrEmpty(value) && File.Exists(value))
        {
            HasSelectedExcel = true;
            SelectedExcelFileName = Path.GetFileName(value);
            ExcelUploadStatus = "✅ Excel文件已加载";
        }
        else
        {
            HasSelectedExcel = false;
            SelectedExcelFileName = string.Empty;
            ExcelUploadStatus = "未选择Excel文件";
        }
    }

    [RelayCommand]
    private async Task GenerateBatchComments()
    {
        if (IsProcessing) return;

        try
        {
            IsProcessing = true;
            OutputResult = "正在生成批量点评...";

            var comments = new List<StudentComment>();
            var studentNames = new[] { "刘浩鑫", "吴若凡", "陈一鸣", "余炜权", "陈奕鸣", "郭培玥", "顾文昊", "黎姿希", "叶亦铭", "夏俊岳" };

            for (int i = 0; i < Math.Min(GenerateCount, studentNames.Length); i++)
            {
                var comment = await _aiService.GenerateCommentAsync(
                    studentNames[i], 
                    SelectedSubject, 
                    StartGrade, 
                    Difficulty);

                comments.Add(new StudentComment
                {
                    StudentName = studentNames[i],
                    Subject = SelectedSubject,
                    StartGrade = StartGrade,
                    EndGrade = EndGrade,
                    Difficulty = Difficulty,
                    Comment = comment
                });

                OutputResult = $"已生成 {i + 1}/{GenerateCount} 条评语...";
                await Task.Delay(100); // 避免API调用过快
            }

            var fileName = $"批量点评_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
            var filePath = await _excelService.CreateStudentCommentsExcelAsync(comments, fileName);

            OutputResult = $"=== 批量点评生成完成 ===\n\n" +
                          $"课程名称: {SelectedSubject}\n" +
                          $"开始年级: {StartGrade}\n" +
                          $"结束年级: {EndGrade}\n" +
                          $"难度等级: {Difficulty}\n" +
                          $"学生姓名: {string.Join("、", comments.Select(c => c.StudentName))}\n\n" +
                          $"Excel结果文件已保存: {filePath}";
        }
        catch (Exception ex)
        {
            OutputResult = $"生成失败: {ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    [RelayCommand]
    private async Task SelectExcelFile()
    {
        // 通过事件通知View执行文件选择
        await Task.Run(() => 
        {
            OutputResult = "请在弹出的对话框中选择Excel文件...";
        });
    }

    [RelayCommand]
    private async Task CreateTemplate()
    {
        try
        {
            IsProcessing = true;
            var fileName = $"学生信息模板_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
            var filePath = await _excelService.CreateTemplateExcelAsync(fileName);
            OutputResult = $"模板文件已创建: {filePath}";
        }
        catch (Exception ex)
        {
            OutputResult = $"创建模板失败: {ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    [RelayCommand]
    private async Task ProcessExcel()
    {
        if (string.IsNullOrEmpty(SelectedExcelPath))
        {
            OutputResult = "请先选择Excel文件";
            return;
        }

        try
        {
            IsProcessing = true;
            OutputResult = "正在读取Excel文件...";
            
            // 读取Excel文件中的学生姓名
            var studentNames = await _excelService.ReadStudentNamesFromExcelAsync(SelectedExcelPath);
            OutputResult = $"已读取到 {studentNames.Count} 名学生，正在生成AI评语...";

            // 为每个学生生成AI评语
            var comments = new List<StudentComment>();
            for (int i = 0; i < studentNames.Count; i++)
            {
                var studentName = studentNames[i];
                OutputResult = $"正在为学生 {studentName} 生成评语... ({i + 1}/{studentNames.Count})";

                var comment = await _aiService.GenerateCommentAsync(
                    studentName, 
                    SelectedSubject, 
                    StartGrade, 
                    Difficulty);

                comments.Add(new StudentComment
                {
                    StudentName = studentName,
                    Subject = SelectedSubject,
                    StartGrade = StartGrade,
                    EndGrade = EndGrade,
                    Difficulty = Difficulty,
                    Comment = comment
                });

                await Task.Delay(100); // 避免API调用过快
            }

            // 生成新的Excel文件
            var fileName = $"AI扩写评语_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
            var filePath = await _excelService.CreateStudentCommentsExcelAsync(comments, fileName);

            OutputResult = $"=== Excel处理完成 ===\n\n" +
                          $"源文件: {SelectedExcelPath}\n" +
                          $"处理学生数: {studentNames.Count}\n" +
                          $"课程名称: {SelectedSubject}\n" +
                          $"年级范围: {StartGrade} - {EndGrade}\n" +
                          $"难度等级: {Difficulty}\n" +
                          $"学生列表: {string.Join("、", studentNames)}\n\n" +
                          $"AI扩写结果文件已保存: {filePath}";
        }
        catch (Exception ex)
        {
            OutputResult = $"处理失败: {ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    [RelayCommand]
    private async Task SelectImage()
    {
        // 通过事件通知View执行图片选择
        await Task.Run(() => 
        {
            OutputResult = "请在弹出的对话框中选择图片文件...";
        });
    }

    [RelayCommand]
    private async Task ExtractImageText()
    {
        try
        {
            IsProcessing = true;
            OutputResult = "正在从图像头进行取...";
            
            // 模拟图像识别
            await Task.Delay(2000);
            OutputResult = "图像头提取完成！";
        }
        catch (Exception ex)
        {
            OutputResult = $"提取失败: {ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    [RelayCommand]
    private async Task AnalyzeImage()
    {
        if (string.IsNullOrEmpty(SelectedImagePath))
        {
            OutputResult = "请先选择图片";
            return;
        }

        try
        {
            IsProcessing = true;
            OutputResult = "正在分析图片...";

            // 检查图片文件是否存在
            if (!_imageService.IsValidImageFile(SelectedImagePath))
            {
                OutputResult = "无效的图片文件格式";
                return;
            }

            // 获取图片信息
            var (width, height, fileSize) = await _imageService.GetImageInfoAsync(SelectedImagePath);
            OutputResult = $"正在处理图片 ({width}x{height}, {fileSize / 1024}KB)...";

            // 转换图片为Base64
            var base64Image = await _imageService.ConvertImageToBase64Async(SelectedImagePath);
            OutputResult = $"正在调用AI分析服务 ({SelectedAIModel})...";

            // 根据选择的模型调用不同的AI服务
            string analysisResult;
            if (SelectedAIModel.StartsWith("Qwen-VL-Max"))
            {
                // 使用增强的视觉模型
                var imageFormat = _qwenVLService.DetectImageFormat(base64Image);
                OutputResult = $"使用 Qwen-VL-Max 模型分析图像 (格式: {imageFormat})...";
                analysisResult = await _qwenVLService.AnalyzeStudentRosterAsync(base64Image, imageFormat);
            }
            else
            {
                // 使用原版模型
                OutputResult = "使用 Qwen-Omni-Turbo 模型分析图像...";
                var analysisPrompt = @"请仔细分析这张图片，这是一张学生点名表、课程名单或课程表的照片。

**分析要求：**
1. 课程名称：查找课程标题、科目名称（如：乐高机器人搭建、科学实验、GESP图形化编程、传感器搭建、3D打印笔模型设计、智能穿越机器人、趣味思维、创意创客电路、车航模等）
2. 年级信息：查找年级标识（如：一年级、二年级、三年级、四年级、五年级、六年级，或1-3年级这样的范围）
3. 难度等级：查找难度标识（如：入门、基础、提高、竞赛、初级、中级、高级等）
4. 学生姓名：**重点识别**图片中的所有中文学生姓名，通常是2-4个汉字组成的人名

**严格按照以下格式输出，不要添加其他内容：**

课程名称：[识别到的具体课程名称]
年级：[识别到的年级信息]
难度等级：[识别到的难度等级]
学生总数：[识别到的学生数量]
学生姓名：[用、分隔的所有学生姓名]

**注意事项：**
- 如果某项信息无法识别，请填写""未识别""
- 学生姓名请仔细识别，包括图片中的所有中文人名
- 请确保识别的姓名是真实的中文人名，不要包含课程名称或其他词汇
- 多个姓名用中文顿号""、""分隔";

                analysisResult = await _aiService.AnalyzeImageAsync(base64Image, analysisPrompt);
            }

            // Smart 解析AI分析结果
            var analysisInfo = ParseAnalysisResult(analysisResult);
            
            // 自动填充到批量点评生成区域
            AutoFillBatchGenerationFields(analysisInfo);

            // 解析学生姓名
            var studentNames = analysisInfo.StudentNames;
            RecognizedStudents = $"识别到 {studentNames.Count}名学生";

            // 设置预览数据
            HasPreviewData = true;
            PreviewCourseName = analysisInfo.CourseName;
            PreviewGrade = analysisInfo.Grade;
            PreviewDifficulty = analysisInfo.Difficulty;
            PreviewStudentNames = studentNames;
            PreviewSummary = $"课程：{analysisInfo.CourseName}\n年级：{analysisInfo.Grade}\n难度：{analysisInfo.Difficulty}\n学生数量：{studentNames.Count}人\n学生名单：{string.Join("、", studentNames)}";

            // 更新格式化的学生名单显示字符串
            PreviewStudentNamesDisplay = string.Join("、", studentNames);
            
            // 设置可编辑的学生名单
            EditableStudentNames = string.Join("、", studentNames);

            // 匹配并显示课程介绍
            MatchAndShowCourseIntroduction(analysisInfo.CourseName);

            OutputResult = "=== 🎯 图片识别完成 ===\n\n" +
                          $"📸 图片路径: {SelectedImagePath}\n" +
                          $"🤖 使用模型: {SelectedAIModel}\n" +
                          (SelectedAIModel.StartsWith("Qwen-VL-Max") ? 
                              $"📊 模型特点: {_qwenVLService.GetModelInfo()}\n\n" : 
                              "📊 模型特点: Qwen-Omni-Turbo - 通用多模态模型\n\n") +
                          "🔍 AI识别结果:\n" +
                          $"{analysisResult}\n\n" +
                          "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n" +
                          "📋 解析后的识别结果:\n" +
                          $"📚 识别课程: {analysisInfo.CourseName}\n" +
                          $"🎓 识别年级: {analysisInfo.Grade}\n" +
                          $"⭐ 识别难度: {analysisInfo.Difficulty}\n" +
                          $"👥 学生总数: {studentNames.Count}人\n" +
                          $"📝 学生姓名: {string.Join("、", studentNames)}\n\n" +
                          "✅ 自动填充结果:\n" +
                          $"• 选择科目: {SelectedSubject}{(SelectedSubject == "未识别" ? " (未能匹配)" : " ✓")}\n" +
                          $"• 开始年级: {StartGrade}{(StartGrade == "未识别" ? " (未能匹配)" : " ✓")}\n" +
                          $"• 结束年级: {EndGrade}{(EndGrade == "未识别" ? " (未能匹配)" : " ✓")}\n" +
                          $"• 难度程度: {Difficulty}{(Difficulty == "未识别" ? " (未能匹配)" : " ✓")}\n" +
                          $"• 生成数量: {GenerateCount}\n\n" +
                          "💡 请确认识别结果是否正确，可在上方编辑学生名单，然后点击下方\"确认生成Excel\"按钮进行下一步操作。";
        }
        catch (Exception ex)
        {
            OutputResult = $"分析失败: {ex.Message}";
            HasPreviewData = false;
            PreviewStudentNamesDisplay = string.Empty;
            EditableStudentNames = string.Empty;
        }
        finally
        {
            IsProcessing = false;
        }
    }

    // 新增：从可编辑字符串中解析学生名单
    private List<string> GetCurrentStudentNames()
    {
        if (string.IsNullOrWhiteSpace(EditableStudentNames))
        {
            return PreviewStudentNames;
        }

        // 解析用户编辑的学生名单
        var names = EditableStudentNames
            .Split(new[] { '、', ',', '，', ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(name => name.Trim())
            .Where(name => !string.IsNullOrWhiteSpace(name) && name.Length >= 2 && name.Length <= 4)
            .Distinct()
            .ToList();

        return names.Count > 0 ? names : PreviewStudentNames;
    }

    [RelayCommand]
    private async Task ConfirmGenerateExcel()
    {
        if (!HasPreviewData || string.IsNullOrWhiteSpace(EditableStudentNames))
        {
            OutputResult = "没有可用的预览数据，请先进行图片识别或输入学生名单";
            return;
        }

        // 获取当前的学生名单（可能是用户编辑后的）
        var currentStudentNames = GetCurrentStudentNames();
        if (currentStudentNames.Count == 0)
        {
            OutputResult = "学生名单为空，请检查输入的学生姓名";
            return;
        }

        try
        {
            IsProcessing = true;
            ShowProgress = true;
            _processStartTime = DateTime.Now; // 记录开始时间
            
            // 初始化进度，增加更多详细步骤
            TotalProgress = currentStudentNames.Count + 4; // 评语生成 + 模板验证 + 生成评价表 + 生成汇总表
            CurrentProgress = 0;
            UpdateProgress(0, "🚀 初始化生成流程，准备开始...");

            UpdateProgress(1, "🔍 检查模板资源是否存在...");
            
            // 检查模板资源是否存在
            if (!_templateService.IsTemplateExists())
            {
                OutputResult = "❌ 错误：模板资源不存在！\n模板文件已设置为内置资源，如果出现此错误，请检查程序是否正确编译。";
                return;
            }

            UpdateProgress(2, "⚙️ 准备生成参数和课程信息...");

            // 使用预览数据生成Excel
            var courseName = (SelectedSubject != "未识别" && !string.IsNullOrEmpty(SelectedSubject)) 
                ? SelectedSubject 
                : (!string.IsNullOrEmpty(PreviewCourseName) && PreviewCourseName != "未识别") 
                    ? PreviewCourseName 
                    : "默认课程";
            
            var gradeName = (StartGrade != "未识别" && !string.IsNullOrEmpty(StartGrade)) 
                ? StartGrade 
                : (!string.IsNullOrEmpty(PreviewGrade) && PreviewGrade != "未识别") 
                    ? PreviewGrade 
                    : "三年级";

            var difficultyName = (Difficulty != "未识别" && !string.IsNullOrEmpty(Difficulty)) 
                ? Difficulty 
                : (!string.IsNullOrEmpty(PreviewDifficulty) && PreviewDifficulty != "未识别") 
                    ? PreviewDifficulty 
                    : "入门";

            // 获取用户确认的课程介绍（如果有的话）
            var courseIntroduction = HasCourseIntroduction ? CourseIntroduction : string.Empty;

            // 并发生成AI评语，提高处理速度
            var comments = new List<StudentComment>();
            UpdateProgress(3, $"🤖 开始为 {currentStudentNames.Count} 位学生并发生成AI评语...");

            // 创建并发任务，限制并发数量避免API限制
            var semaphore = new SemaphoreSlim(3, 3); // 最多3个并发请求
            var tasks = currentStudentNames.Select(async (studentName, index) =>
            {
                await semaphore.WaitAsync();
                try
                {
                    var progressIndex = 3 + index + 1;
                    UpdateProgress(progressIndex, $"🤖 正在为学生 {studentName} 生成个性化AI评语... ({index + 1}/{currentStudentNames.Count})");

                    var comment = await _aiService.GenerateCommentAsync(studentName, courseName, gradeName, difficultyName, false); // 使用qwen-turbo非流式处理，速度更快

                    UpdateProgress(progressIndex, $"✅ 学生 {studentName} - AI评语生成完成！({index + 1}/{currentStudentNames.Count})");

                    return new StudentComment
                    {
                        StudentName = studentName,
                        Subject = courseName,
                        StartGrade = gradeName,
                        EndGrade = gradeName,
                        Difficulty = difficultyName,
                        Comment = comment
                    };
                }
                catch (Exception ex)
                {
                    var progressIndex = 3 + index + 1;
                    UpdateProgress(progressIndex, $"⚠️ 学生 {studentName} - 评语生成失败，使用默认评语 ({index + 1}/{currentStudentNames.Count})");

                    return new StudentComment
                    {
                        StudentName = studentName,
                        Subject = courseName,
                        StartGrade = gradeName,
                        EndGrade = gradeName,
                        Difficulty = difficultyName,
                        Comment = $"该学生在{courseName}课程中表现良好，学习态度认真，建议继续保持并加强实践能力。（评语生成失败：{ex.Message}）"
                    };
                }
                finally
                {
                    semaphore.Release();
                }
            });

            // 等待所有任务完成
            var results = await Task.WhenAll(tasks);
            comments.AddRange(results);

            // 保存生成的评语数据供预览使用
            LastGeneratedComments = comments.ToList();
            OnPropertyChanged(nameof(HasGeneratedComments));

            UpdateProgress(currentStudentNames.Count + 3, "📊 开始使用内置模板生成个人评价表...");

            // 使用模板为每个学生生成评价表，传递用户确认的课程介绍
            var generatedFiles = await _templateService.GenerateStudentReportsAsync(
                currentStudentNames, 
                courseName, 
                gradeName, 
                _aiService,
                courseIntroduction); // 传递课程介绍

            UpdateProgress(currentStudentNames.Count + 4, "📝 正在生成学生名单汇总表...");

            // 同时生成简单的汇总Excel
            var summaryFileName = $"学生名单汇总_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
            var summaryPath = await _excelService.CreateStudentCommentsExcelAsync(comments, summaryFileName);
            
            UpdateProgress(TotalProgress, "🎉 所有表格生成完成！准备显示结果...");

            // 获取文件夹路径
            var outputFolderPath = generatedFiles.Count > 0 ? Path.GetDirectoryName(generatedFiles[0]) : "桌面";
            var folderName = generatedFiles.Count > 0 ? Path.GetFileName(Path.GetDirectoryName(generatedFiles[0])) : "未知文件夹";
            
            OutputResult = "=== 🎉 Excel表格生成完成 ===\n\n" +
                          "✅ 使用的生成参数:\n" +
                          $"• 课程名称: {courseName}\n" +
                          $"• 年级信息: {gradeName}\n" +
                          $"• 难度等级: {difficultyName}\n" +
                          $"• 学生数量: {currentStudentNames.Count}人\n" +
                          $"• 学生名单: {string.Join("、", currentStudentNames)}\n\n" +
                          "📊 生成的文件:\n" +
                          $"📋 学生名单汇总: {summaryPath}\n\n" +
                          $"📁 评价表文件夹: {folderName}\n" +
                          $"📍 文件夹路径: {outputFolderPath}\n\n" +
                          "📄 个人评价表文件列表:\n" +
                          string.Join("\n", generatedFiles.Select((file, index) => $"   {index + 1}. {Path.GetFileName(file)}")) + "\n\n" +
                          "🎉 完成！所有评价表已基于模板生成，包含:\n" +
                          "   • 学生个人信息 (A1:课程名称, B3:学生姓名, D3:年级, F3:日期)\n" +
                          "   • 随机评分等级 (F6-F19随机A、A+评分)\n" +
                          "   • 课程总结内容 (A20行)\n" +
                          "   • AI个性化评语 (A22行开始)\n\n" +
                          "💡 提示: 所有评价表文件已统一保存到专门文件夹中，便于管理和使用！\n\n" +
                          "🔍 想要预览和修改评语内容？点击下方的\"预览修改评语\"按钮！";

            // 重置预览数据
            HasPreviewData = false;
            PreviewStudentNamesDisplay = string.Empty;
            EditableStudentNames = string.Empty;
        }
        catch (Exception ex)
        {
            OutputResult = $"生成Excel失败: {ex.Message}";
        }
        finally
        {
            IsProcessing = false;
            ShowProgress = false;
        }
    }

    private void UpdateProgress(int current, string taskDescription)
    {
        CurrentProgress = current;
        CurrentTaskDescription = taskDescription;
        ProgressPercentage = TotalProgress > 0 ? (double)current / TotalProgress * 100 : 0;
        
        // 更新输出结果显示进度，提供更详细的信息
        var progressBar = GenerateProgressBar(ProgressPercentage);
        var timeEstimate = EstimateRemainingTime(current, TotalProgress);
        
        OutputResult = $"📊 总进度: {current}/{TotalProgress} ({ProgressPercentage:F1}%)\n" +
                      $"{progressBar}\n" +
                      $"🔄 当前任务: {taskDescription}\n" +
                      $"⏰ 预计剩余时间: {timeEstimate}\n" +
                      $"💡 提示: 正在使用AI技术为每位学生生成个性化评语";
    }

    private string GenerateProgressBar(double percentage)
    {
        var barLength = 30;
        var filledLength = (int)(percentage / 100.0 * barLength);
        var bar = new string('█', filledLength) + new string('░', barLength - filledLength);
        return $"[{bar}]";
    }

    private string EstimateRemainingTime(int current, int total)
    {
        if (current == 0) return "计算中...";
        
        var elapsed = DateTime.Now.Subtract(_processStartTime);
        var avgTimePerItem = elapsed.TotalSeconds / current;
        var remainingItems = total - current;
        var remainingSeconds = remainingItems * avgTimePerItem;
        
        if (remainingSeconds < 60)
            return $"{remainingSeconds:F0}秒";
        else if (remainingSeconds < 3600)
            return $"{remainingSeconds / 60:F1}分钟";
        else
            return $"{remainingSeconds / 3600:F1}小时";
    }

    private DateTime _processStartTime;

    private void MatchAndShowCourseIntroduction(string courseName)
    {
        try
        {
            if (!string.IsNullOrEmpty(courseName) && courseName != "未识别")
            {
                var introduction = _courseIntroductionService.GetCourseIntroduction(courseName);
                CourseIntroduction = introduction;
                HasCourseIntroduction = true;
                ShowCourseIntroduction = true;
            }
            else
            {
                HasCourseIntroduction = false;
                ShowCourseIntroduction = false;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"匹配课程介绍失败: {ex.Message}");
            HasCourseIntroduction = false;
            ShowCourseIntroduction = false;
        }
    }

    [RelayCommand]
    private void ToggleCourseIntroduction()
    {
        ShowCourseIntroduction = !ShowCourseIntroduction;
    }

    [RelayCommand]
    private void ResetCourseIntroduction()
    {
        var courseName = (SelectedSubject != "未识别" && !string.IsNullOrEmpty(SelectedSubject))
            ? SelectedSubject
            : (!string.IsNullOrEmpty(PreviewCourseName) && PreviewCourseName != "未识别")
                ? PreviewCourseName
                : "默认课程";
        
        CourseIntroduction = _courseIntroductionService.GetCourseIntroduction(courseName);
    }

    [RelayCommand]
    private void ReloadCourseIntroductions()
    {
        try
        {
            var result = _courseIntroductionService.ReloadCourseIntroductions();
            var filePath = _courseIntroductionService.GetCourseIntroductionFilePath();
            
            OutputResult = $"🔄 课程介绍重新加载完成！\n\n{result}\n\n" +
                          $"📄 使用的文件: {filePath}\n\n" +
                          $"💡 提示: 如果修改了课程介绍文件，可以使用此功能热重载，无需重启程序。";
            
            // 如果当前有课程介绍显示，则更新它
            if (HasCourseIntroduction)
            {
                ResetCourseIntroduction();
            }
        }
        catch (Exception ex)
        {
            OutputResult = $"❌ 重新加载课程介绍失败: {ex.Message}";
        }
    }

    [RelayCommand]
    private async Task QuickGenerateExcel()
    {
        if (!HasPreviewData || string.IsNullOrWhiteSpace(EditableStudentNames))
        {
            OutputResult = "没有可用的预览数据，请先进行图片识别或输入学生名单";
            return;
        }

        // 获取当前的学生名单（可能是用户编辑后的）
        var currentStudentNames = GetCurrentStudentNames();
        if (currentStudentNames.Count == 0)
        {
            OutputResult = "学生名单为空，请检查输入的学生姓名";
            return;
        }

        try
        {
            IsProcessing = true;
            OutputResult = "正在快速生成学生名单Excel...";

            // 使用预览数据
            var courseName = (SelectedSubject != "未识别" && !string.IsNullOrEmpty(SelectedSubject)) 
                ? SelectedSubject 
                : (!string.IsNullOrEmpty(PreviewCourseName) && PreviewCourseName != "未识别") 
                    ? PreviewCourseName 
                    : "默认课程";
            
            var gradeName = (StartGrade != "未识别" && !string.IsNullOrEmpty(StartGrade)) 
                ? StartGrade 
                : (!string.IsNullOrEmpty(PreviewGrade) && PreviewGrade != "未识别") 
                    ? PreviewGrade 
                    : "三年级";

            var difficultyName = (Difficulty != "未识别" && !string.IsNullOrEmpty(Difficulty)) 
                ? Difficulty 
                : (!string.IsNullOrEmpty(PreviewDifficulty) && PreviewDifficulty != "未识别") 
                    ? PreviewDifficulty 
                    : "入门";

            // 使用快速生成方法，不调用AI
            var quickFileName = $"学生名单_快速_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
            var quickFilePath = await _excelService.CreateQuickStudentListExcelAsync(
                currentStudentNames, 
                courseName, 
                gradeName, 
                difficultyName, 
                quickFileName);

            OutputResult = "=== ⚡ 快速生成完成 ===\n\n" +
                          "✅ 生成参数:\n" +
                          $"• 课程名称: {courseName}\n" +
                          $"• 年级信息: {gradeName}\n" +
                          $"• 难度等级: {difficultyName}\n" +
                          $"• 学生数量: {currentStudentNames.Count}人\n" +
                          $"• 学生名单: {string.Join("、", currentStudentNames)}\n\n" +
                          "📊 生成的文件:\n" +
                          $"📋 学生名单Excel: {quickFilePath}\n\n" +
                          "🎉 快速生成模式特点:\n" +
                          "   • ⚡ 无需等待AI生成评语，瞬间完成\n" +
                          "   • 📝 包含完整学生名单和课程信息\n" +
                          "   • 📊 提供汇总统计信息\n" +
                          "   • 🔄 后续可手动填写评语或备注\n\n" +
                          "💡 提示: 如需AI评语和详细评价表，请使用上方的\"确认生成Excel表格\"按钮";

            // 不重置预览数据，用户还可以选择完整生成
        }
        catch (Exception ex)
        {
            OutputResult = $"快速生成失败: {ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    private class AnalysisInfo
    {
        public string CourseName { get; set; } = "未识别";
        public string Grade { get; set; } = "未识别";
        public string Difficulty { get; set; } = "入门";
        public List<string> StudentNames { get; set; } = new();
        public int StudentCount { get; set; } = 0;
    }

    private AnalysisInfo ParseAnalysisResult(string analysisResult)
    {
        var info = new AnalysisInfo();
        
        try
        {
            var lines = analysisResult.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            
            foreach (var line in lines)
            {
                var cleanLine = line.Trim();
                
                // 解析课程名称
                if (cleanLine.Contains("课程名称") || cleanLine.Contains("课程"))
                {
                    var courseName = ExtractValue(cleanLine, new[] { "课程名称：", "课程名称:", "课程：", "课程:" });
                    if (!string.IsNullOrEmpty(courseName))
                    {
                        info.CourseName = courseName;
                    }
                }
                
                // 解析年级 - 支持单个年级和年级范围
                if (cleanLine.Contains("年级"))
                {
                    var grade = ExtractValue(cleanLine, new[] { "年级：", "年级:", "课程级别：", "课程级别:" });
                    if (!string.IsNullOrEmpty(grade))
                    {
                        info.Grade = grade;
                    }
                }
                
                // 解析难度等级
                if (cleanLine.Contains("难度") || cleanLine.Contains("等级"))
                {
                    var difficulty = ExtractValue(cleanLine, new[] { "难度等级：", "难度等级:", "难度：", "难度:" });
                    if (!string.IsNullOrEmpty(difficulty))
                    {
                        info.Difficulty = difficulty;
                    }
                }
                
                // 解析学生姓名
                if (cleanLine.Contains("学生姓名") || cleanLine.Contains("姓名"))
                {
                    var names = ExtractValue(cleanLine, new[] { "学生姓名：", "学生姓名:", "姓名：", "姓名:" });
                    if (!string.IsNullOrEmpty(names))
                    {
                        var nameList = names.Split(new[] { "、", ",", "，", " ", "\t" }, StringSplitOptions.RemoveEmptyEntries)
                                          .Where(n => !string.IsNullOrWhiteSpace(n))
                                          .Select(n => n.Trim())
                                          .ToList();
                        
                        info.StudentNames.AddRange(nameList);
                    }
                }
            }
            
            // 如果没有识别到学生姓名，使用默认名单
            if (info.StudentNames.Count == 0)
            {
                info.StudentNames.AddRange(ExtractStudentNamesFromAnalysis(analysisResult));
            }
            
            info.StudentCount = info.StudentNames.Count;
        }
        catch (Exception ex)
        {
            // 解析失败时使用默认值
            info.StudentNames = ExtractStudentNamesFromAnalysis(analysisResult);
            info.StudentCount = info.StudentNames.Count;
        }
        
        return info;
    }

    private string ExtractValue(string line, string[] prefixes)
    {
        foreach (var prefix in prefixes)
        {
            if (line.Contains(prefix))
            {
                var value = line.Substring(line.IndexOf(prefix) + prefix.Length).Trim();
                return value;
            }
        }
        return string.Empty;
    }

    private void AutoFillBatchGenerationFields(AnalysisInfo analysisInfo)
    {
        try
        {
            // 自动匹配课程科目 - 总是设置值
            var matchedSubject = MatchSubject(analysisInfo.CourseName);
            SelectedSubject = !string.IsNullOrEmpty(matchedSubject) ? matchedSubject : "未识别";
            
            // 自动匹配年级 - 总是设置值
            var matchedGrade = MatchGrade(analysisInfo.Grade);
            var gradeToSet = !string.IsNullOrEmpty(matchedGrade) ? matchedGrade : "未识别";
            StartGrade = gradeToSet;
            EndGrade = gradeToSet; // 开始和结束年级设为相同
            
            // 自动匹配难度 - 总是设置值
            var matchedDifficulty = MatchDifficulty(analysisInfo.Difficulty);
            Difficulty = !string.IsNullOrEmpty(matchedDifficulty) ? matchedDifficulty : "未识别";
            
            // 设置生成数量 - 基于识别到的学生数量
            GenerateCount = analysisInfo.StudentCount > 0 ? Math.Min(analysisInfo.StudentCount, 50) : 10;
            
            // 更新课程信息显示
            CourseInfo = $"课程: {analysisInfo.CourseName} | 学生: {analysisInfo.StudentCount}人 | 年级: {analysisInfo.Grade} | 难度: {analysisInfo.Difficulty}";
        }
        catch (Exception ex)
        {
            // 自动填充失败，设置为"未识别"
            SelectedSubject = "未识别";
            StartGrade = "未识别";
            EndGrade = "未识别";
            Difficulty = "未识别";
            GenerateCount = 10;
            CourseInfo = $"自动填充失败: {ex.Message}";
        }
    }

    private string MatchSubject(string courseName)
    {
        if (string.IsNullOrEmpty(courseName)) return string.Empty;
        
        var lowerCourseName = courseName.ToLower();
        
        // 乐高机器人相关
        if (lowerCourseName.Contains("乐高") || lowerCourseName.Contains("机器人") || 
            lowerCourseName.Contains("lego") || lowerCourseName.Contains("robot") || 
            lowerCourseName.Contains("搭建"))
            return "乐高机器人搭建";
        
        // 科学实验
        if (lowerCourseName.Contains("科学实验") || lowerCourseName.Contains("实验"))
            return "科学实验";
        
        // GESP图形化编程
        if (lowerCourseName.Contains("gesp") && lowerCourseName.Contains("图形化"))
        {
            if (lowerCourseName.Contains("一级") || lowerCourseName.Contains("1级") || lowerCourseName.Contains("（一）"))
                return "GESP图形化编程（一）级";
            if (lowerCourseName.Contains("二级") || lowerCourseName.Contains("2级") || lowerCourseName.Contains("（二）"))
                return "GESP图形化编程（二）级";
            if (lowerCourseName.Contains("三级") || lowerCourseName.Contains("3级") || lowerCourseName.Contains("（三）"))
                return "GESP图形化编程（三）级";
            return "GESP图形化编程（一）级"; // 默认一级
        }
        
        // GESP-Python
        if (lowerCourseName.Contains("gesp") && (lowerCourseName.Contains("python") || lowerCourseName.Contains("py")))
        {
            if (lowerCourseName.Contains("一级") || lowerCourseName.Contains("1级") || lowerCourseName.Contains("（一）"))
                return "GESP-Python（一）级";
            if (lowerCourseName.Contains("二级") || lowerCourseName.Contains("2级") || lowerCourseName.Contains("（二）"))
                return "GESP-Python（二）级";
            if (lowerCourseName.Contains("三级") || lowerCourseName.Contains("3级") || lowerCourseName.Contains("（三）"))
                return "GESP-Python（三）级";
            return "GESP-Python（一）级"; // 默认一级
        }
        
        // GESP-C++
        if (lowerCourseName.Contains("gesp") && (lowerCourseName.Contains("c++") || lowerCourseName.Contains("cpp")))
        {
            if (lowerCourseName.Contains("一级") || lowerCourseName.Contains("1级") || lowerCourseName.Contains("（一）"))
                return "GESP-C++（一）级";
            if (lowerCourseName.Contains("二级") || lowerCourseName.Contains("2级") || lowerCourseName.Contains("（二）"))
                return "GESP-C++（二）级";
            if (lowerCourseName.Contains("三级") || lowerCourseName.Contains("3级") || lowerCourseName.Contains("（三）"))
                return "GESP-C++（三）级";
            return "GESP-C++（一）级"; // 默认一级
        }
        
        // 传感器搭建
        if (lowerCourseName.Contains("传感器") || lowerCourseName.Contains("sensor"))
            return "传感器搭建";
        
        // 3D打印笔模型设计
        if (lowerCourseName.Contains("3d") || lowerCourseName.Contains("打印笔") || 
            lowerCourseName.Contains("模型设计") || lowerCourseName.Contains("3d打印"))
            return "3D打印笔模型设计";
        
        // 智能穿越机器人
        if (lowerCourseName.Contains("智能穿越") || lowerCourseName.Contains("穿越机器人"))
            return "智能穿越机器人";
        
        // 趣味思维
        if (lowerCourseName.Contains("趣味思维") || lowerCourseName.Contains("思维") || 
            lowerCourseName.Contains("逻辑") || lowerCourseName.Contains("thinking"))
            return "趣味思维";
        
        // 创意创客电路
        if (lowerCourseName.Contains("创意创客") || lowerCourseName.Contains("电路") || 
            lowerCourseName.Contains("创客") || lowerCourseName.Contains("circuit"))
            return "创意创客电路";
        
        // 车航模
        if (lowerCourseName.Contains("车航模") || lowerCourseName.Contains("航模") || 
            lowerCourseName.Contains("模型车") || lowerCourseName.Contains("车模"))
            return "车航模";
        
        return string.Empty;
    }

    private string MatchGrade(string grade)
    {
        if (string.IsNullOrEmpty(grade)) return string.Empty;
        
        var lowerGrade = grade.ToLower();
        
        // 如果已经是范围格式，直接返回
        if (lowerGrade.Contains("-") && lowerGrade.Contains("年级"))
        {
            return grade;
        }
        
        // 单个年级匹配
        if (lowerGrade.Contains("一年级") || lowerGrade.Contains("1年级") || lowerGrade.Contains("第一年"))
            return "一年级";
        
        if (lowerGrade.Contains("二年级") || lowerGrade.Contains("2年级") || lowerGrade.Contains("第二年"))
            return "二年级";
        
        if (lowerGrade.Contains("三年级") || lowerGrade.Contains("3年级") || lowerGrade.Contains("第三年"))
            return "三年级";
        
        if (lowerGrade.Contains("四年级") || lowerGrade.Contains("4年级") || lowerGrade.Contains("第四年"))
            return "四年级";
        
        if (lowerGrade.Contains("五年级") || lowerGrade.Contains("5年级") || lowerGrade.Contains("第五年"))
            return "五年级";
        
        if (lowerGrade.Contains("六年级") || lowerGrade.Contains("6年级") || lowerGrade.Contains("第六年"))
            return "六年级";
        
        // 尝试识别数字范围格式
        if (System.Text.RegularExpressions.Regex.IsMatch(lowerGrade, @"\d+-\d+"))
        {
            return grade + (grade.Contains("年级") ? "" : "年级");
        }
        
        return string.Empty;
    }

    private string MatchDifficulty(string difficulty)
    {
        if (string.IsNullOrEmpty(difficulty)) return string.Empty;
        
        var lowerDifficulty = difficulty.ToLower();
        
        if (lowerDifficulty.Contains("入门") || lowerDifficulty.Contains("初级") || 
            lowerDifficulty.Contains("简单") || lowerDifficulty.Contains("starter"))
            return "入门";
        
        if (lowerDifficulty.Contains("基础") || lowerDifficulty.Contains("基本") || 
            lowerDifficulty.Contains("普通") || lowerDifficulty.Contains("basic"))
            return "基础";
        
        if (lowerDifficulty.Contains("提高") || lowerDifficulty.Contains("进阶") || 
            lowerDifficulty.Contains("中等") || lowerDifficulty.Contains("intermediate") ||
            lowerDifficulty.Contains("advanced"))
            return "提高";
        
        if (lowerDifficulty.Contains("竞赛") || lowerDifficulty.Contains("比赛") || 
            lowerDifficulty.Contains("困难") || lowerDifficulty.Contains("挑战") ||
            lowerDifficulty.Contains("competition") || lowerDifficulty.Contains("contest"))
            return "竞赛";
        
        return "入门"; // 默认返回入门
    }

    private List<string> ExtractStudentNamesFromAnalysis(string analysisResult)
    {
        var names = new List<string>();
        
        try
        {
            // 使用正则表达式提取中文姓名
            var namePattern = @"[\u4e00-\u9fa5]{2,4}";
            var matches = System.Text.RegularExpressions.Regex.Matches(analysisResult, namePattern);
            
            // 常见的姓氏列表，用于验证提取的姓名
            var commonSurnames = new HashSet<string> { 
                "王", "李", "张", "刘", "陈", "杨", "赵", "黄", "周", "吴",
                "徐", "孙", "胡", "朱", "高", "林", "何", "郭", "马", "罗",
                "梁", "宋", "郑", "谢", "韩", "唐", "冯", "于", "董", "萧",
                "程", "曹", "袁", "邓", "许", "傅", "沈", "曾", "彭", "吕",
                "苏", "卢", "蒋", "蔡", "贾", "丁", "魏", "薛", "叶", "阎",
                "余", "潘", "杜", "戴", "夏", "钟", "汪", "田", "任", "姜",
                "范", "方", "石", "姚", "谭", "廖", "邹", "熊", "金", "陆",
                "郝", "孔", "白", "崔", "康", "毛", "邱", "秦", "江", "史",
                "顾", "侯", "邵", "孟", "龙", "万", "段", "雷", "钱", "汤"
            };
            
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                var possibleName = match.Value;
                
                // 验证是否是真实姓名：长度2-4字符，且第一个字符是常见姓氏
                if (possibleName.Length >= 2 && possibleName.Length <= 4 && 
                    commonSurnames.Contains(possibleName.Substring(0, 1)))
                {
                    // 避免重复添加
                    if (!names.Contains(possibleName) && 
                        !IsCommonWord(possibleName)) // 排除常见词汇
                    {
                        names.Add(possibleName);
                    }
                }
            }
            
            // 如果通过正则没有找到足够的姓名，尝试按行解析
            if (names.Count < 3)
            {
                var lines = analysisResult.Split('\n', StringSplitOptions.RemoveEmptyEntries);
                foreach (var line in lines)
                {
                    // 查找包含姓名列表的行
                    if (line.Contains("姓名") || line.Contains("学生") || line.Contains("名单"))
                    {
                        // 尝试提取该行中的姓名
                        var lineNames = ExtractNamesFromLine(line);
                        foreach (var name in lineNames)
                        {
                            if (!names.Contains(name))
                            {
                                names.Add(name);
                            }
                        }
                    }
                }
            }
            
            // 移除重复项并限制数量
            return names.Distinct().Take(50).ToList();
        }
        catch (Exception)
        {
            // 如果提取失败，返回空列表而不是默认名单
            return new List<string>();
        }
    }
    
    private bool IsCommonWord(string word)
    {
        // 排除一些常见的非姓名词汇
        var commonWords = new HashSet<string> {
            "学生", "姓名", "课程", "年级", "班级", "老师", "学校", "作业",
            "考试", "成绩", "评语", "家长", "同学", "朋友", "今天", "明天",
            "时间", "地点", "内容", "方法", "结果", "问题", "答案", "题目",
            "练习", "复习", "预习", "课堂", "教室", "图书", "电脑", "手机"
        };
        
        return commonWords.Contains(word);
    }
    
    private List<string> ExtractNamesFromLine(string line)
    {
        var names = new List<string>();
        
        // 移除常见的前缀词汇
        var cleanLine = line;
        var prefixes = new[] { "学生姓名", "姓名", "学生", "名单", ":", "：", "包括", "有" };
        foreach (var prefix in prefixes)
        {
            if (cleanLine.Contains(prefix))
            {
                var index = cleanLine.IndexOf(prefix) + prefix.Length;
                if (index < cleanLine.Length)
                {
                    cleanLine = cleanLine.Substring(index);
                }
            }
        }
        
        // 按分隔符分割
        var parts = cleanLine.Split(new[] { "、", ",", "，", " ", "\t", "；", ";" }, 
                                   StringSplitOptions.RemoveEmptyEntries);
        
        foreach (var part in parts)
        {
            var trimmed = part.Trim();
            if (trimmed.Length >= 2 && trimmed.Length <= 4 && 
                System.Text.RegularExpressions.Regex.IsMatch(trimmed, @"^[\u4e00-\u9fa5]+$"))
            {
                names.Add(trimmed);
            }
        }
        
        return names;
    }

    [RelayCommand]
    private void SaveResult()
    {
        try
        {
            var fileName = $"分析结果_{DateTime.Now:yyyyMMdd_HHmmss}.txt";
            var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName);
            File.WriteAllText(filePath, OutputResult);
            OutputResult += $"\n\n结果已保存到: {filePath}";
        }
        catch (Exception ex)
        {
            OutputResult += $"\n\n保存失败: {ex.Message}";
        }
    }

    [RelayCommand]
    private void ClearResult()
    {
        OutputResult = string.Empty;
        RecognizedStudents = "识别到 0名学生";
    }

    [RelayCommand]
    private void OpenPreviewView()
    {
        if (LastGeneratedComments.Count > 0)
        {
            ShowPreviewView = true;
        }
        else
        {
            OutputResult = "没有可预览的评语数据，请先生成评语";
        }
    }

    [RelayCommand]
    private void ClosePreviewView()
    {
        ShowPreviewView = false;
    }

    [RelayCommand]
    private async Task AutoFillFromTable()
    {
        try
        {
            IsProcessing = true;
            OutputResult = "正在从名表自动填充...";
            
            // 模拟自动填充
            await Task.Delay(1500);
            
            CourseInfo = "课程: 乐高机器人搭建 | 学生: 10人";
            SelectedSubject = "乐高机器人搭建";
            StartGrade = "三年级";
            EndGrade = "三年级";
            Difficulty = "入门";
            GenerateCount = 10;
            
            OutputResult = "自动填充完成！请点击'批量生成评语'开始生成。";
        }
        catch (Exception ex)
        {
            OutputResult = $"自动填充失败: {ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    [RelayCommand]
    private async Task CheckTemplate()
    {
        try
        {
            IsProcessing = true;
            OutputResult = "正在检查模板资源...";
            
            // 检查Excel模板
            var templateInfo = await _templateService.GetTemplateInfoAsync();
            
            // 检查课程介绍文件
            var courseIntroInfo = GetCourseIntroductionInfo();
            
            var templateStatus = _templateService.IsTemplateExists() ? "✅ 正常" : "❌ 缺失";
            
            OutputResult = "=== 📋 资源检查结果 ===\n\n" +
                          "📄 Excel模板资源:\n" +
                          templateInfo + "\n" +
                          $"状态: {templateStatus}\n\n" +
                          "📚 课程介绍资源:\n" +
                          courseIntroInfo + "\n\n" +
                          "📝 使用说明:\n" +
                          "• 上传点名表图片进行识别\n" +
                          "• 系统会自动为每个学生生成个人评价表\n" +
                          "• 评价表基于内置模板资源自动填写内容\n" +
                          "• 课程介绍支持外部txt文件热更新\n" +
                          "• 将'课程介绍.txt'放在程序目录下即可自动使用外部文件";
        }
        catch (Exception ex)
        {
            OutputResult = $"检查资源失败: {ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    private string GetCourseIntroductionInfo()
    {
        try
        {
            var externalFilePath = "课程介绍.txt";
            var hasExternalFile = File.Exists(externalFilePath);
            var courseCount = _courseIntroductionService.GetAllCourseNames().Count;
            
            if (hasExternalFile)
            {
                var fileInfo = new FileInfo(externalFilePath);
                var lastModified = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                var fileSize = (fileInfo.Length / 1024.0).ToString("F1") + " KB";
                
                return $"文件路径: {Path.GetFullPath(externalFilePath)}\n" +
                       $"文件大小: {fileSize}\n" +
                       $"最后修改: {lastModified}\n" +
                       $"课程数量: {courseCount}\n" +
                       $"状态: ✅ 使用外部文件";
            }
            else
            {
                var internalResourcePath = "avares://AvaAI批量点评系统/Assets/课程介绍.txt";
                return $"文件路径: {internalResourcePath}\n" +
                       $"课程数量: {courseCount}\n" +
                       $"状态: 📦 使用内置资源\n" +
                       $"提示: 可将'课程介绍.txt'放在程序目录下进行自定义";
            }
        }
        catch (Exception ex)
        {
            return $"检查课程介绍文件失败: {ex.Message}";
        }
    }

    [RelayCommand]
    private async Task QuickTestModels()
    {
        if (string.IsNullOrEmpty(SelectedImagePath))
        {
            OutputResult = "请先选择图片进行模型对比测试";
            return;
        }

        try
        {
            IsProcessing = true;
            OutputResult = "正在进行AI模型对比测试...\n这将使用两个不同的模型分析同一张图片，以便您比较效果。";

            // 获取图片信息
            var base64Image = await _imageService.ConvertImageToBase64Async(SelectedImagePath);
            var imageFormat = _qwenVLService.DetectImageFormat(base64Image);

            OutputResult = "🔍 正在使用 Qwen-VL-Max 模型分析...";
            var vlMaxResult = await _qwenVLService.AnalyzeStudentRosterAsync(base64Image, imageFormat);

            OutputResult = "🔍 正在使用 Qwen-Omni-Turbo 模型分析...";
            var simplePrompt = "请识别这张图片中的课程名称、年级、难度等级和学生姓名信息。";
            var omniResult = await _aiService.AnalyzeImageAsync(base64Image, simplePrompt);

            OutputResult = "=== 🆚 AI模型对比测试结果 ===\n\n" +
                          $"📸 测试图片: {SelectedImagePath}\n" +
                          $"🖼️ 图片格式: {imageFormat.ToUpper()}\n\n" +
                          "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n" +
                          "🥇 **Qwen-VL-Max 模型结果** (专业视觉模型-已优化)\n" +
                          $"📊 模型特点: {_qwenVLService.GetModelInfo()}\n\n" +
                          $"🔍 识别结果:\n{vlMaxResult}\n\n" +
                          "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n" +
                          "🥈 **Qwen-Omni-Turbo 模型结果** (通用多模态模型)\n" +
                          "📊 模型特点: 通用多模态处理，支持多种任务类型，流式响应\n\n" +
                          $"🔍 识别结果:\n{omniResult}\n\n" +
                          "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n" +
                          "💡 **优化说明:**\n" +
                          "• 已统一两个模型的流式响应处理机制\n" +
                          "• VL-Max 模型现在应该能正确识别年级、难度等信息\n" +
                          "• 如果识别结果仍有差异，请检查图片质量和内容清晰度\n\n" +
                          "🎯 **使用建议:**\n" +
                          "• Qwen-VL-Max: 专业视觉模型，在复杂图像和手写识别方面更准确\n" +
                          "• Qwen-Omni-Turbo: 通用模型，处理速度快，适合清晰的打印文字\n" +
                          "• 建议优先使用 Qwen-VL-Max 获得最佳识别效果";
        }
        catch (Exception ex)
        {
            OutputResult = $"模型对比测试失败: {ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    // ================================
    // AI评语扩写功能相关命令
    // ================================

    [RelayCommand]
    private async Task GenerateAIComment()
    {
        if (string.IsNullOrWhiteSpace(StudentNameForComment))
        {
            OutputResult = "请先输入学生姓名";
            return;
        }

        if (IsProcessing) return;

        try
        {
            IsProcessing = true;
            OutputResult = $"正在为学生 {StudentNameForComment} 生成AI评语...";

            // 构建评语生成提示
            var prompt = $"请为学生{StudentNameForComment}生成一份{SelectedSubject}学科的{StartGrade}年级{Difficulty}难度的学习评语。" +
                        $"要求：1. 积极正面，具有建设性；" +
                        $"2. 符合该年级学生特点；" +
                        $"3. 体现{Difficulty}难度的学习内容；" +
                        $"4. 字数只能是150字，逻辑要完整合理。" +
                        $"5.开头不能出现“尊敬的学生家长，我是XX的班主任”直接XX同学即可" +
                        $"6.结尾不能出现此致敬礼等内容。" +
                        $"7. 此致 敬礼！ 您的孩子， 日期：2025年X月X日 这些不能出现！" +
                        $"“老师”不能出现";

            // 调用Omni模型生成评语（用于评语生成任务）
            var comment = await _aiService.GenerateCommentAsync(
                StudentNameForComment, 
                SelectedSubject, 
                StartGrade, 
                Difficulty);

            GeneratedComment = comment;
            HasGeneratedComment = true;

            OutputResult = $"=== ✨ AI评语生成完成 ===\n\n" +
                          $"👤 学生姓名: {StudentNameForComment}\n" +
                          $"📚 学科科目: {SelectedSubject}\n" +
                          $"🎓 年级等级: {StartGrade}\n" +
                          $"⭐ 难度程度: {Difficulty}\n\n" +
                          $"📝 生成的评语:\n{comment}\n\n" +
                          "💡 您可以在上方的评语框中编辑内容，然后点击复制按钮使用。";
        }
        catch (Exception ex)
        {
            OutputResult = $"生成AI评语失败: {ex.Message}";
            HasGeneratedComment = false;
        }
        finally
        {
            IsProcessing = false;
        }
    }













    [RelayCommand]
    private async Task RegenerateComment()
    {
        if (string.IsNullOrWhiteSpace(StudentNameForComment))
        {
            OutputResult = "请先输入学生姓名";
            return;
        }

        if (IsProcessing) return;

        try
        {
            IsProcessing = true;
            OutputResult = $"正在重新生成 {StudentNameForComment} 的AI评语...";

            // 使用不同的生成策略重新生成评语
            var prompt = $"请为学生{StudentNameForComment}重新生成一份{SelectedSubject}学科的{StartGrade}年级{Difficulty}难度的学习评语。" +
                        $"要求：1. 与之前的评语风格有所不同；2. 更加个性化和具体；3. 突出学生的优点和进步空间；4. 语言亲切自然，富有鼓励性。";

            var newComment = await _aiService.GenerateCommentAsync(
                StudentNameForComment, 
                SelectedSubject, 
                StartGrade, 
                Difficulty);

            GeneratedComment = newComment;
            HasGeneratedComment = true;

            OutputResult = $"=== 🔄 AI评语重新生成完成 ===\n\n" +
                          $"👤 学生姓名: {StudentNameForComment}\n" +
                          $"📚 学科科目: {SelectedSubject}\n" +
                          $"🎓 年级等级: {StartGrade}\n" +
                          $"⭐ 难度程度: {Difficulty}\n\n" +
                          $"📝 重新生成的评语:\n{newComment}\n\n" +
                          "💡 每次重新生成都会产生不同风格的评语，您可以多次尝试选择最合适的版本。";
        }
        catch (Exception ex)
        {
            OutputResult = $"重新生成AI评语失败: {ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    [RelayCommand]
    private async Task ExportModifiedData()
    {
        if (LastGeneratedComments?.Count == 0)
        {
            OutputResult = "没有可导出的数据";
            return;
        }

        try
        {
            IsProcessing = true;
            OutputResult = "正在导出修改后的评语...";

            // 获取课程名称和年级信息
            var firstComment = LastGeneratedComments.First();
            var courseName = firstComment.Subject ?? "未知课程";
            var grade = firstComment.StartGrade ?? "三年级";

            var generatedFiles = await _excelService.CreateStudentCommentsWithAbilityFromTemplateAsync(
                LastGeneratedComments, courseName, grade);

            var folderPath = Path.GetDirectoryName(generatedFiles.First());
            var folderName = Path.GetFileName(folderPath);

            OutputResult = $"✅ 导出成功！\n文件夹已保存到桌面：{folderName}\n\n" +
                          $"📊 导出统计：\n" +
                          $"• 学生数量：{LastGeneratedComments.Count}\n" +
                          $"• 生成文件数：{generatedFiles.Count}\n" +
                          $"• 包含能力评语的学生：{LastGeneratedComments.Count(c => c.AbilityEvaluation?.EvaluationItems?.Count > 0)}\n" +
                          $"• 导出时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss}\n\n" +
                          $"📁 生成的文件：\n" +
                          string.Join("\n", generatedFiles.Select(f => $"• {Path.GetFileName(f)}"));
        }
        catch (Exception ex)
        {
            OutputResult = $"❌ 导出失败：{ex.Message}";
        }
        finally
        {
            IsProcessing = false;
        }
    }

    // 清理资源
    public void Dispose()
    {
        _aiService?.Dispose();
        ImagePreviewBitmap?.Dispose();
    }
}
